# encoding: utf-8
from app.extensions import log, db
from flask_restplus import Resource
from app.extensions.api import Namespace
from . import schemas, parameters
from flask_restplus_patched import Parameters
from app.modules.common.schemas import BaseSchema
from .models import Zone
from app.modules.common.utils import DbCommit, checkToken
from app.modules.agent.resources import syncZoneAndApps

api = Namespace('zone', description = "区域记录")  # pylint: disable=invalid-name


@api.route('/')
class List(Resource):
    @api.parameters(Parameters())
    @api.response(schemas.ZoneListSchema(many = False))
    def get(self, args, **kwargs):
        """
        查询区域列表，同步用
        :param args:
        :return:
        """
        log.info("============== start get zone list ==============")
        _list = Zone.query.all()
        return {'success': True, 'msg': '', 'data': _list}


@api.route('/add')
class AddZone(Resource):
    @api.parameters(parameters.ZoneAddParameters())
    @api.response(BaseSchema(many = False))
    @checkToken
    def post(self, args, **kwargs):
        """
        添加zone
        :param args:
        :return:
        """
        log.info("============== start add zone ==============")
        _zone_code = args['zone_code']
        _zone_alias = args['zone_alias']
        _parent_code = args['parent_code']
        _zone_title = args['zone_title']
        _order_no = args['order_no']
        _zone = Zone.query.filter_by(zone_code = _zone_code).first()
        if _zone is not None:
            _msg = '区域 %s 已存在' % _zone_code
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        _zone = Zone.query.filter_by(zone_alias = _zone_alias).first()
        if _zone is not None:
            _msg = '区域 %s 已存在' % _zone_alias
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        _zone = Zone.query.filter_by(zone_title = _zone_title).first()
        if _zone is not None:
            _msg = '区域 %s 已存在' % _zone_title
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        _zone = Zone.query.filter_by(order_no = _order_no).first()
        if _zone is not None:
            _msg = '序号 %s 已存在' % _order_no
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        if _parent_code is not None:
            _zone = Zone.query.filter_by(zone_code = _parent_code).first()
            if _zone is None:
                _msg = '父级区域 %s 不存在' % _parent_code
                log.error('============== %s ==============' % _msg)
                return {'success': False, 'msg': _msg}

        _zone = Zone(zone_code = _zone_code, parent_code = _parent_code, zone_title = _zone_title, zone_desc = None,
                     available = True, zone_alias = _zone_alias, order_no = _order_no)
        db.session.add(_zone)
        _rtn = DbCommit()
        # 调用agent更新
        syncZoneAndApps()
        return _rtn
